﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace ThresholdAssistant.Tools.Extensions
{
    /// <summary>
    /// 流水号生成规则
    /// </summary>
    public static class SerialNoExtensions
    {
        /// <summary>
        /// 将微信ID或者群ID转换成编号（32的MD5值，content为空的情况，返回空字符串）
        /// </summary>
        public static string ToSerialNo(this string content, bool lowercase = true)
        {
            if (!string.IsNullOrWhiteSpace(content))
            {
                return Md5Hash(content, lowercase);
            }
            return string.Empty;
        }

        /// <summary>
        /// 32位MD5加密
        /// </summary>
        /// <param name="content"></param>
        /// <param name="lowercase"></param>
        /// <returns></returns>
        public static string Md5Hash(string content, bool lowercase = true)
        {
            using var md5Provider = new MD5CryptoServiceProvider();
            byte[] data = md5Provider.ComputeHash(Encoding.UTF8.GetBytes(content));
            string hash = BitConverter.ToString(data);
            hash = hash.Replace("-", string.Empty);
            if (lowercase)
            {
                return hash.ToLower();
            }
            return hash;
        }
    }
}